package com.example.shortlink.config;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.spring.boot.ConfigurationCustomizer;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import com.mybatisflex.spring.boot.SqlSessionFactoryBeanCustomizer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;


/**
 * @author MSI
 */
@Slf4j
@Configuration
@MapperScan("com.example.shortlink.dao.mapper")
public class MybatisFlexConfig implements MyBatisFlexCustomizer, ConfigurationCustomizer, SqlSessionFactoryBeanCustomizer {

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        log.info("Mybatis Flex Configuration");
        // 关闭 flex banner
        flexGlobalConfig.setPrintBanner(false);
        // 开启审计功能
        AuditManager.setAuditEnable(true);
        // 设置 SQL 审计收集器
        AuditManager.setMessageCollector(consoleMessageCollector ->
                log.info("Sql 耗时:{}ms => {},",
                        consoleMessageCollector.getElapsedTime(),
                        consoleMessageCollector.getFullSql())
        );
    }

    @Override
    public void customize(FlexConfiguration flexConfiguration) {
        log.info("Mybatis Configuration");
        // 打印 sql 到控制台
        flexConfiguration.setLogImpl(StdOutImpl.class);
    }

    @Override
    public void customize(SqlSessionFactoryBean sqlSessionFactoryBean) {
        log.info("SqlSession Configuration");
    }
}
